import 'dart:async';
import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_rtk/core/flutter_api.dart';
import 'package:flutter_rtk/extension/color_extension.dart';
import 'package:flutter_rtk/models/login_model.dart';
import 'package:flutter_rtk/router/index.dart';
import 'package:flutter_rtk/service/event_bus_service.dart';
import 'package:flutter_rtk/service/events/watch_cdt_event.dart';
import 'package:flutter_rtk/utils/cdt_utils.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:oktoast/oktoast.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:provider/provider.dart';

import 'common/constants.dart';
import 'models/app_model.dart';
import 'models/user_info_model.dart';
import 'service/connectivity_service.dart';
import 'service/database_service.dart';
import 'service/store_service.dart';
import 'utils/image_picker_utils.dart';

void main() {
  Zone.current.fork(specification: ZoneSpecification(
    handleUncaughtError: (self, parent, zone, error, stackTrace) {
      debugPrint("error stackTrace $error, $stackTrace");
      EasyLoading.dismiss();
    },
  )).run(() async {
    WidgetsFlutterBinding.ensureInitialized();
    // 竖屏模式
    await SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]);
    setUp().then((v) {
      runApp(MultiProvider(
        providers: [
          ChangeNotifierProvider(create: (context) => LoginModel()),
          ChangeNotifierProvider(create: (context) => AppModel()),
          ChangeNotifierProvider(create: (context) => UserInfoModel()),
        ],
        child: ScreenUtilInit(
          designSize: const Size(750, 1334),
          minTextAdapt: true,
          splitScreenMode: true,
          builder: (BuildContext context, Widget? child) => const SaleAnalyzerApp(),
        ),
      ));
    });
  });
}

bool isStartWatcher = false;

setUp() async {
  // 初始化本机存储
  await StoreService.to.init();
  // 初始化数据库
  await DatabaseService.to.init();
  // 初始化网络监听
  await ConnectivityService.to.init();
  // 初始化图片选择器
  await ImagePickerUtils.init();
  // 初始化插件
  await FlutterApi.registerPlugins();
  if (kDebugMode) {
    await StoreService.to.setString(AppConstants.baseUrl, "https://cip-test.sinoma-ncdri.cn");
  }
  if (kReleaseMode) {
    await StoreService.to.setString(AppConstants.baseUrl, "https://cip.sinoma-ncdri.cn");
  }
  // 权限申请
  await Permission.locationWhenInUse.request();
  await Permission.camera.request();
  await Permission.storage.request();
  // 初始化eventbus
  EventBusService.init();
  //设置Android头部的导航栏透明
  if (Platform.isAndroid) {
    SystemUiOverlayStyle systemUiOverlayStyle = const SystemUiOverlayStyle(statusBarColor: Colors.transparent);
    SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);
  }
  // 监测测地通是否能获取到数据
  if (Platform.isAndroid) {
    if (!isStartWatcher) {
      CDTUtils.start((EventChannel channel) {
        channel.receiveBroadcastStream().listen((data) {
          EventBusService.fire(WatchCDTEvent(true));
          CDTUtils.remove();
        });
        isStartWatcher = true;
      });
    }
  }
}

final GlobalKey<NavigatorState> globalNavigatorKey = GlobalKey();

class SaleAnalyzerApp extends StatelessWidget {
  const SaleAnalyzerApp({super.key});

  @override
  Widget build(BuildContext context) {
    return OKToast(
      movingOnWindowChange: false,
      child: MaterialApp(
        debugShowCheckedModeBanner: true,
        title: '数字建造平台',
        navigatorKey: globalNavigatorKey,
        builder: EasyLoading.init(
          builder: (_, child) {
            return MediaQuery(
              data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),
              child: child!,
            );
          },
        ),
        theme: ThemeData(
          splashColor: Colors.transparent,
          // 设置点击无水波
          highlightColor: Colors.transparent,
          splashFactory: NoSplash.splashFactory,
          primarySwatch: AppConstants.brandColor.toMaterialColor(),
          scaffoldBackgroundColor: AppConstants.pageBackgroundColor,
          appBarTheme: AppBarTheme(
            titleTextStyle: TextStyle(color: Colors.black, fontSize: 32.sp, fontWeight: FontWeight.w600),
            iconTheme: const IconThemeData(color: Colors.black),
          ),
        ),
        initialRoute: AppRouters.login,
        onGenerateRoute: (settings) => AppRouters().onGenerateRoute(settings),
      ),
    );
  }
}
